package com.example.saifly.inPagePlan.article;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.Activity;
import com.example.common.Application.MyApplication;
import com.example.common.Retrofit.RetrofitHelper;
import com.example.saifly.R;

import java.util.Timer;
import java.util.TimerTask;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;


public class ArticleDetailActivity extends Activity {

    private ImageView ivReturn;      //返回图标
    private Button btCollect;    //收藏图标
    private WebView wvArticle;

    private String articleId;   //文章ID
    private int flag=0;      //记录文章是否收藏

    private SharedPreferences sharedPreferences= MyApplication.getContext().getSharedPreferences("config", Context.MODE_PRIVATE);

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_plan_article_detail;
    }

    @Override
    protected void init() {
        super.init();

        String articleContent="获取文章失败";

        ivReturn = findViewById(R.id.articleDetail_return);
        btCollect=findViewById(R.id.article_detail_collect);
        wvArticle=findViewById(R.id.article_detile_content);

        new Thread(new Runnable() {
            @Override
            public void run() {
                String phoneNo=sharedPreferences.getString("uid","default");
                String articleID="";
                if (getIntent()!= null)
                {
                    int key = getIntent().getIntExtra("key",0);
                    if(key==1)
                    {
                        articleID=getIntent().getStringExtra("DailyNursingArticleID");   //根据键名获取数据
                    }
                    else if(key==2)
                    {
                        articleID=getIntent().getStringExtra("EatingHealthArticleID");
                    }
                    else if(key==3)
                    {
                        articleID=getIntent().getStringExtra("SpecialSeasonArticleID");
                    }
                    else if(key==4)
                    {
                        articleID=getIntent().getStringExtra("RecommendArticleID");
                    }
                    else if(key==5)
                    {
                        articleID=getIntent().getStringExtra("CollectionArticleID");
                    }

                }
//                Log.d("文章ID", "logData: "+articleID);
                isCollectedArticle(phoneNo,articleID);
//                Log.d("文章", "logData: "+flag);
               runOnUiThread(new Runnable() {
                   @Override
                   public void run() {
                       initCollectButton();    //初始化收藏图标
                   }
               });
            }
        }).start();

        if (getIntent()!= null)
        {
            int key = getIntent().getIntExtra("key",0);
            if(key==1)
            {
                articleContent=getIntent().getStringExtra("DailyNursingArticleContent");   //根据键名获取数据
            }
            else if(key==2)
            {
                articleContent=getIntent().getStringExtra("EatingHealthArticleContent");
            }
            else if(key==3)
            {
                articleContent=getIntent().getStringExtra("SpecialSeasonArticleContent");
            }
            else if(key==4)
            {
                articleContent=getIntent().getStringExtra("RecommendArticleContent");
            }
            else if(key==5)
            {
                articleContent=getIntent().getStringExtra("CollectionArticleContent");
            }
        }
        articleContent=articleContent.replace("<img","<img style=max-width:100%;height:auto");
        wvArticle.loadDataWithBaseURL(null,articleContent,"text/html","UTF-8",null);

        btCollect.setOnClickListener(new addListeners());     //对收藏按钮进行监听

        doJump();
    }

    protected void initCollectButton() {
        switch(flag){
            case 0:
                btCollect.setActivated(false);
                flag=1;
                break;
            case 1:
                btCollect.setActivated(true);
                flag=0;
                break;
        }
    }

    private interface collectdArticle {
        @Headers({"Content-Type:application/json"})
        @POST("/manage/collectdArticle")
        Call<ResponseBody> articleCollecting(@Body JSONObject jsonObject);
    }

    private void articleCollecting(String phoneNumber,String articleID) {
        RetrofitHelper retrofitHelper = new RetrofitHelper();
        Retrofit retrofit = retrofitHelper.getRetrofit();

        collectdArticle apiGetArticleDetail = retrofit.create(collectdArticle.class);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("patientPhone",phoneNumber);
        jsonObject.put("articalId",articleID);
        Log.d("啦啦啦啦", "logData: "+jsonObject);

        Call<ResponseBody> call = apiGetArticleDetail.articleCollecting(jsonObject);
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            String jsonResult=response.body().string();
            Log.d("啦啦啦啦", "logData: "+jsonResult);
            JSONObject result = JSON.parseObject(jsonResult);

            if (result.getInteger("code") == 1) {
                //获取的code为1 说明请求成功
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        Toast toast=Toast.makeText(ArticleDetailActivity.this, "收藏成功", Toast.LENGTH_LONG);
                        showMyToast(toast,10*1000);
                    }
                });
            } else {
                //请求失败
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        Toast toast=Toast.makeText(ArticleDetailActivity.this, "收藏失败，请重新尝试", Toast.LENGTH_LONG);
                        showMyToast(toast,10*500);// 设置显示时间  一次10ms,显示500次，即显示5s
                    }
                });
            }
        } catch (Exception e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(ArticleDetailActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
    }

    private interface CancelCollectArticle{              //删除收藏
        @Headers({"Content-Type:application/json"})
        @POST("/manage/CancelCollectArticle")
        Call<ResponseBody> deleteCollectedArticle(@Body JSONObject jsonObject);
    }

    private void deleteCollectedArticle(String phoneNumber,String articleID) {
        RetrofitHelper retrofitHelper = new RetrofitHelper();
        Retrofit retrofit = retrofitHelper.getRetrofit();

        CancelCollectArticle apiDeleteCollection = retrofit.create(CancelCollectArticle.class);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("patientPhone",phoneNumber);
        jsonObject.put("articalId",articleID);
//        Log.d("啦啦啦啦", "logData: "+jsonObject);

        Call<ResponseBody> call = apiDeleteCollection.deleteCollectedArticle(jsonObject);
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            String jsonResult=response.body().string();
            Log.d("取消收藏", "logData: "+jsonResult);
            JSONObject result = JSON.parseObject(jsonResult);
            Log.d("取消收藏", "logData: "+result);

            if (result.getInteger("code") == 1) {
                //获取的code为1 说明请求成功
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast toast=Toast.makeText(ArticleDetailActivity.this, "取消收藏成功", Toast.LENGTH_LONG);
                        showMyToast(toast,10*1000);
                    }
                });
            } else {
                //请求失败
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        Toast toast=Toast.makeText(ArticleDetailActivity.this, "取消收藏失败，请重新尝试", Toast.LENGTH_LONG);
                        showMyToast(toast,10*500);// 设置显示时间  一次10ms,显示500次，即显示5s
                    }
                });
            }
        } catch (Exception e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(ArticleDetailActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
    }

    private interface JudgeCollectArticle {
        @Headers({"Content-Type:application/json"})
        @POST("/manage/JudgeCollectArticle")
        Call<ResponseBody> isCollectedArticle(@Body JSONObject jsonObject);
    }

    private void isCollectedArticle(String phoneNumber,String articleID) {
        RetrofitHelper retrofitHelper = new RetrofitHelper();
        Retrofit retrofit = retrofitHelper.getRetrofit();

        JudgeCollectArticle apiIsCollectedArticle = retrofit.create(JudgeCollectArticle.class);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("patientPhone",phoneNumber);
        jsonObject.put("articalId",articleID);
//        Log.d("啦啦啦啦", "logData: "+jsonObject);

        Call<ResponseBody> call = apiIsCollectedArticle.isCollectedArticle(jsonObject);
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            String jsonResult=response.body().string();
//            Log.d("判断", "logData: "+jsonResult);
            JSONObject result = JSON.parseObject(jsonResult);
//            Log.d("判断", "logData: "+result);

            if (result.getInteger("code") == 1) {
                flag=result.getInteger("result");
//                Log.d("12345", "logData: "+flag);

            } else {
                //请求失败
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        Toast toast=Toast.makeText(ArticleDetailActivity.this, "请刷新", Toast.LENGTH_LONG);
                        showMyToast(toast,10*500);// 设置显示时间  一次10ms,显示500次，即显示5s
                    }
                });
            }
        } catch (Exception e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(ArticleDetailActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
    }

    public void showMyToast(final Toast toast, final int cnt) {
        final Timer timer =new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                toast.show();
            }
        },0,3000);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                toast.cancel();
                timer.cancel();
            }
        }, cnt );
    }

    private class addListeners implements Button.OnClickListener
    {
        @Override
        public void onClick (View v) {
            switch(flag){
                case 0:
                    btCollect.setActivated(false);
                    flag = 1;
                    break;
                case 1:
                    btCollect.setActivated(true);
                    flag = 0;
                    break;
            }
            if(btCollect.isActivated()==true)      //收藏
            {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String phoneNo=sharedPreferences.getString("uid","default");
                        String articleID="";
                        if (getIntent()!= null)
                        {
                            int key = getIntent().getIntExtra("key",0);
                            if(key==1)
                            {
                                articleID=getIntent().getStringExtra("DailyNursingArticleID");   //根据键名获取数据
                            }
                            else if(key==2)
                            {
                                articleID=getIntent().getStringExtra("EatingHealthArticleID");
                            }
                            else if(key==3)
                            {
                                articleID=getIntent().getStringExtra("SpecialSeasonArticleID");
                            }
                            else if(key==4)
                            {
                                articleID=getIntent().getStringExtra("RecommendArticleID");
                            }
                            else if(key==5)
                            {
                                articleID=getIntent().getStringExtra("CollectionArticleID");
                            }
                        }
                        Log.d("文章ID", "logData: "+articleID);
                        articleCollecting(phoneNo,articleID);
                    }
                }).start();
            }
            else      //取消收藏
            {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String phoneNo=sharedPreferences.getString("uid","default");
                        String articleID="";
                        if (getIntent()!= null)
                        {
                            int key = getIntent().getIntExtra("key",0);
                            if(key==1)
                            {
                                articleID=getIntent().getStringExtra("DailyNursingArticleID");   //根据键名获取数据
                            }
                            else if(key==2)
                            {
                                articleID=getIntent().getStringExtra("EatingHealthArticleID");
                            }
                            else if(key==3)
                            {
                                articleID=getIntent().getStringExtra("SpecialSeasonArticleID");
                            }
                            else if(key==4)
                            {
                                articleID=getIntent().getStringExtra("RecommendArticleID");
                            }
                            else if(key==5)
                            {
                                articleID=getIntent().getStringExtra("CollectionArticleID");
                            }
                        }
                        Log.d("文章ID", "logData: "+articleID);
                        deleteCollectedArticle(phoneNo,articleID);
                    }
                }).start();
            }
        }
    }
    //设置页面跳转逻辑
    private void doJump()
    {
        ivReturn.setOnClickListener(view -> finish());
    }

}
